package com.zuiacsn.forum.controller;

import com.zuiacsn.forum.common.AppResult;
import com.zuiacsn.forum.common.ResultCode;
import com.zuiacsn.forum.config.AppConfig;
import com.zuiacsn.forum.exception.ApplicationException;
import com.zuiacsn.forum.model.Article;
import com.zuiacsn.forum.model.Board;
import com.zuiacsn.forum.model.User;
import com.zuiacsn.forum.service.IArticleService;
import com.zuiacsn.forum.service.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "文章接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IArticleService articleService;
    @Resource
    private IBoardService boardService;

    /**
     * 发布新帖子
     * @param boardId 版块Id
     * @param title 文章标题
     * @param content 文章内容
     * @return
     */
    @ApiOperation("发布新帖")
    @PostMapping("/create")
    public AppResult create (HttpServletRequest request,
                             @ApiParam("版块Id") @RequestParam("boardId") @NonNull Long boardId,
                             @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                             @ApiParam("文章内容") @RequestParam("content") @NonNull String content) {
        // 校验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 用户已禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 版块的校验
        Board board = boardService.selectById(boardId.longValue());
        if (board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            // 返回响应
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }

        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        // 调用Service
        articleService.create(article);
        // 响应
        return AppResult.success();
    }

    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(
            @ApiParam("版块Id") @RequestParam(value = "boardId",required = false)Long boardId){

        List<Article> articles;
        if (boardId == null) {
            // 如果传入的参数为空，查询所有
            articles = articleService.selectAll();
        } else {
            // 如果传入的版块Id不为空，查询指定版块下的帖子列表
            articles = articleService.selectAllByBoardId(boardId);
        }

        // 结果是否为空
        if (articles == null) {
            articles = new ArrayList<>();
        }
        // 响应结果
        System.out.println(articles);
        return AppResult.success(articles);
    }

    @ApiOperation("根据帖子Id获取帖子详情")
    @GetMapping("details")
    public AppResult<Article> getDetails(HttpServletRequest request,
            @ApiParam("帖子Id") @RequestParam(value = "id",required = false) Long id){

        // 从session中获取用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        Article article = articleService.selectDetailById(id);
        if(article == null){
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 判断当前用户是否为作者
        if(user.getId().equals(article.getUserId())){
            article.setOwn(true);
        }

        return AppResult.success(article);
    }

    @ApiOperation("更新帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("帖子Id") @RequestParam(value = "id") @NonNull Long id,
                            @ApiParam("帖子标题") @RequestParam(value = "title") @NonNull String title,
                            @ApiParam("帖子内容") @RequestParam(value = "content") @NonNull String content){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 判断用户是否禁言
        if(user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        Article article = articleService.selectById(id);
        // 判断帖子是否不存在
        if(article == null){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        // 判断用户是不是作者
        if(id.equals(article.getUserId())){
            log.warn(ResultCode.FAILED_UNAUTHORIZED.toString());
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }

        // 判断帖子是否被删除
        if (article.getDeleteState() == 1 || article.getState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        log.info("帖子更新成功 Article id = "+article.getId()+",用户id = "+user.getId());
        // 执行修改
        articleService.modify(id,title,content);
        return AppResult.success();
    }

    @ApiOperation("点赞帖子")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request, @ApiParam("帖子Id") @RequestParam(value = "id") @NonNull Long id){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 判断用户是否禁言
        if(user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        articleService.thumbsUpById(id);
        return AppResult.success();
    }

    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,@ApiParam("帖子Id") @RequestParam(value = "id") @NonNull Long id){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 判断用户是否禁言
        if(user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        Article article = articleService.selectById(id);
        // 判断帖子是否不存在
        if(article == null){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        // 判断用户是不是作者
        if(id.equals(article.getUserId())){
            log.warn(ResultCode.FAILED_UNAUTHORIZED.toString());
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }

        // 判断帖子是否被删除
        if (article.getDeleteState() == 1 || article.getState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        // 删除帖子
        articleService.deleteById(id);

        return AppResult.success();
    }

    @ApiOperation("根据用户id获取帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                                   @ApiParam("用户Id") @RequestParam(value = "userId",required = false) Long userId){


        // 如果userid为空,从session中获取用户id
        if(userId == null){
            HttpSession session = request.getSession(false);
            User user = (User)session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }

        List<Article> articles = articleService.selectByUserId(userId);
        return AppResult.success(articles);
    }



}
